package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.micrometer.core.instrument.Meter;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.enums.common.DataScopeEnum;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.mapper.SysTenantMapper;
import org.jeecg.modules.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description: 租户渠道管理
 * @Date:   2019-07-11
 * @Version: V1.0
 */
@Service
@Slf4j
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {
    @Autowired
    private SysTenantMapper sysTenantMapper;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysScopeService sysScopeService;
    @Autowired
    private ISysScopeDepartService sysScopeDepartService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Override
    public List<SysTenant> queryChannelTreeLists() {
        return sysTenantMapper.queryChannelTreeLists();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(SysTenant sysTenant) {
        //step1.校验code是否重复
        int count = this.count(Wrappers.<SysTenant>query().lambda().eq(SysTenant::getName,sysTenant.getName()));
        if (count > 0){
            throw new JeecgBootException("渠道名称系统中已存在！");
        }
        count = sysUserService.getServerCountByAccount(sysTenant.getAdminAccount());
        if (count > 0){
            throw new JeecgBootException("管理员账号系统中已存在！");
        }
        Long maxCode = sysTenantMapper.getMaxCode();
        maxCode++;
        sysTenant.setId(maxCode.toString());
        sysTenant.setCode(maxCode);
        if (sysTenant.getStartTime() == null){
            sysTenant.setStartTime(new Date());
        }
        //step2.创建渠道
        sysTenant.setStatus("0");
        this.save(sysTenant);
        log.info(sysTenant.getId());
        //step3.创建组织机构
        SysDepart sysDepart = new SysDepart();
        sysDepart.setId(sysTenant.getId()); //约定: 必须和tenantId一致,因为一级机构parentId为空,无法和sys_tenant进行关联了,故2者id一样
        sysDepart.setDepartName(sysTenant.getName());
        sysDepart.setTenantId(sysTenant.getId());
        sysDepart.setDepartOrder(0);
        sysDepart.setDepartProperty(CommonConstant.DEPART_PROPERTY_COMPANY);
        sysDepart.setOrgType("1");
        sysDepartService.serverSave(sysDepart);
        //step4.创建系统管理员角色
        SysRole sysRole = new SysRole();
        sysRole.setTenantId(sysTenant.getId());
        sysRole.setRoleName(DataScopeEnum.DATA_SCOPE_TENANT_ADMIN.getDesc());
        sysRole.setRoleCode("subAdmin");
        sysRole.setRoleType(DataScopeEnum.DATA_SCOPE_TENANT_ADMIN.getCode());
        sysRole.setDescription(DataScopeEnum.DATA_SCOPE_TENANT_ADMIN.getDesc());
        sysRoleService.serverSave(sysRole);
        //step5.创建作用域 - 系统管理员
        SysScope sysScope = new SysScope();
        sysScope.setTenantId(sysTenant.getId());
        sysScope.setScopeName(sysTenant.getName());
        sysScope.setScopeType(DataScopeEnum.DATA_SCOPE_TENANT_ADMIN.getCode());
        sysScope.setDescription("全公司范围");
        sysScopeService.serverSave(sysScope);
        //step6.设置作用域 - 机构 关联
        SysScopeDepart sysScopeDepart = new SysScopeDepart();
        sysScopeDepart.setId(String.valueOf(IdWorker.getId()));
        sysScopeDepart.setTenantId(sysTenant.getId());
        sysScopeDepart.setScopeId(sysScope.getId());
        sysScopeDepart.setDepartId(sysDepart.getId());
        sysScopeDepart.setHalfStatus(1);
        sysScopeDepartService.serverSave(sysScopeDepart);
        //step7.创建管理员账号
        SysUser sysUser = new SysUser();
        sysUser.setId(String.valueOf(IdWorker.getId()));
        sysUser.setTenantId(sysTenant.getId());
        sysUser.setDepartId(sysDepart.getId());
        sysUser.setCompanyId(sysDepart.getId());
        sysUser.setRealname(sysDepart.getDepartName());
        sysUser.setUsername(sysTenant.getAdminAccount());
        String salt = oConvertUtils.randomGen(8);
        sysUser.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), "admin", salt);
        sysUser.setPassword(passwordEncode);
        sysUser.setStatus(1);
        sysUserService.serverSave(sysUser);
        //step8.用户 - 角色 - 作用域  关联
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setId(String.valueOf(IdWorker.getId()));
        sysUserRole.setUserId(sysUser.getId());
        sysUserRole.setTenantId(sysTenant.getId());
        sysUserRole.setScopeId(sysScope.getId());
        sysUserRole.setRoleId(sysRole.getId());
        sysUserRoleService.serverSave(sysUserRole);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(SysTenant sysTenant) {
        SysTenant oldTenant = this.getById(sysTenant.getId());
        if (oldTenant == null) {
            throw new JeecgBootException("渠道系统中不存在!");
        }
        if (!oldTenant.getName().equals(sysTenant.getName())){  //名称修改
            int count = this.count(Wrappers.<SysTenant>query().lambda().eq(SysTenant::getName,sysTenant.getName()));
            if (count > 0){
                throw new JeecgBootException("渠道名称系统中已存在！");
            }
            sysDepartService.serverUpdateName(sysTenant.getId(),sysTenant.getName());//修改公司名称
        }
        if (!oldTenant.getAdminAccount().equals(sysTenant.getAdminAccount())){
            int count = sysUserService.getServerCountByAccount(sysTenant.getAdminAccount());
            if (count > 0){
                throw new JeecgBootException("管理员账号系统中已存在！");
            }
            //更新账号和密码
            SysUser sysUser = new SysUser();
            String salt = oConvertUtils.randomGen(8);
            String passwordEncode = PasswordUtil.encrypt(sysTenant.getAdminAccount(), "admin", salt);
            sysUser.setUsername(sysTenant.getAdminAccount());
            sysUser.setSalt(salt);
            sysUser.setPassword(passwordEncode);
            sysUserService.serverUpdateByName(sysUser,oldTenant.getAdminAccount());
        }
        return this.updateById(sysTenant);
    }

    @Override
    public List<SysTenant> getChannelList() {
        return sysTenantMapper.getChannelList();
    }
}
